<?php
namespace app\user2\controller;

use cmf\controller\BaseController;
use app\user2\model\UserModel;

/**
 * 个人中心
 */
class IndexController extends BaseController
{
    protected function checkLoginStatus()
    {
        $user=session("user");
        if($user===false){
            $this->error("用户未登录");
        }
        return $user;
    }
    public function index()
    {
        $user=$this->checkLoginStatus();
        return json($user);
    }
    public function register()
    {
        return $this->fetch("register");
    }
    public function doRegister()
    {
        $nickname=input("nickname");
        $password=input("password");
        if(!$nickname||!$password){
            $this->error("用户名和密码不能为空");
        }
        $um=new UserModel();
        $user=$um->register($nickname,$password);
        if(!$user){
            $this->error($um->getError());
        }
        $this->success("注册成功",url("index"));
    }
    public function login()
    {
        return $this->fetch("login");
    }
    public function doLogin()
    {
        $uid=input("user_id");
        $nickname=input("nickname");
        $password=input("password");
        if($uid){
            $where=["id"=>$uid];
        }
        elseif($nickname){
            $where=["nickname"=>$nickname];
        }
        else{
            $this->error("用户id或昵称不能为空");
        }
        if(!$password){
            $this->error("密码不能为空");
        }
        $um=new UserModel();
        $user=$um->login($where,$password);
        if(!$user){
            $this->error($um->getError());
        }
        $this->success("登陆成功",url("index"));
    }
    public function updateInfo()
    {
        return $this->fetch("updateInfo");
    }
    public function doUpdateInfo()
    {
        $user=$this->checkLoginStatus();

        $update=[];
        $nickname=input("nickname");
        if($nickname){
            $update["nickname"]=$nickname;
        }

        $um=new UserModel();
        $result = $um->allowField(["nickname"])->isUpdate(true)->save($_REQUEST, ["id"=>$user["id"]]);
        if($result===false){
            $this->error("修改用户信息失败");
        }
        $user=array_merge($user,$update);
        session("user",$user);
        $this->success("修改成功",url("index"));
    }
    public function updatePassword()
    {

    }
    public function getBackPassword()
    {

    }
    //删除用户
    public function remove()
    {
        $user=$this->checkLoginStatus();
        $um=new UserModel();
        $result=$um->where(["id"=>$user["id"]])->delete();
        if($result===false){
            $this->error("删除用户失败");
        }
        $this->success("删除成功",url("register"));
    }
}